package com.woniu.cq.medical.component;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.woniu.cq.medical.dao.DoctorMapper;
import com.woniu.cq.medical.entity.Doctor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;

import java.util.HashSet;
import java.util.Set;

/**
 * @BelongsProject: medical
 * @BelongsPackage: com.example.medical.component
 * @Author: rofus
 * @CreateTime: 2020-09-05 11:09
 * @Description: 安全框架
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm  {
    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Doctor doctor=(Doctor)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roleSet = doctorMapper.findRoleValueById(doctor.getDoctorId());
        authorizationInfo.setRoles(roleSet);
        Set<String> permSet = doctorMapper.findPermValueById(doctor.getDoctorId());
        System.out.println(permSet);
        Set<String> permissionSet = new HashSet<>(permSet);
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("进入验证:{}",authenticationToken.getPrincipal());
        String userNo=(String) authenticationToken.getPrincipal();
        int userId=Integer.parseInt(userNo);
        Doctor doctor = doctorMapper.findByDoctorId(userId);
        if(doctor==null){
            throw new UnknownAccountException("用户名或密码不正确");
        }
        return new SimpleAuthenticationInfo(doctor,doctor.getDoctorPassword(),getName());
    }
}
